<template>
    <div class="app-container">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="客户状态" clearable style="width: 200px">
                <el-option label="启用" value="启用"></el-option>
                <el-option label="停用" value="停用"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="客户编号" align="center" prop="customerId" :show-overflow-tooltip="true" />
            <el-table-column label="客户名称" align="center" prop="customerName" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isActive === 1 ? 'success' : 'danger'">{{ scope.row.isActive  === 1 ? '启用' : '停用' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                <el-button
                  size="mini"
                  type="text"
                  :icon="scope.row.isActive === 1 ? 'el-icon-ban' : 'el-icon-check'"
                  :style="scope.row.isActive === 1 ? 'color:#F56C6C' : 'color:#67C23A'"
                  @click="scope.row.isActive === 1 ? handleDisable(scope.row) : handleEnable(scope.row)">
                  {{ scope.row.isActive === 1 ? '禁用' : '启用' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-col>
      </el-row>

      <!-- 新增/修改客户对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="客户编号" prop="customerId">
            <el-input v-model="form.customerId" placeholder="请输入客户编号" maxlength="30" />
          </el-form-item>
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="form.customerName" placeholder="请输入客户名称" maxlength="16" />
          </el-form-item>
          <el-form-item label="状态" prop="isActive">
            <el-radio-group v-model="form.isActive">
              <el-radio label="1">启用</el-radio>
              <el-radio label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 查看客户对话框 -->
      <el-dialog :title="title" :visible.sync="openView" width="500px" append-to-body>
        <el-form ref="viewForm" :model="form" label-width="80px">
          <!-- 查看模式下禁用输入框 -->
          <el-form-item label="客户编号" prop="customerId">
            <el-input v-model="form.customerId" disabled maxlength="30" />
          </el-form-item>
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="form.customerName" disabled maxlength="50" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-tag :type="form.isActive === 1 ? 'success' : 'danger'">{{ form.isActive === 1 ? '启用' : '停用' }}</el-tag>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- 查看模式只保留取消按钮 -->
          <el-button @click="cancelView">关 闭</el-button>
        </div>
      </el-dialog>
      <!-- 新增状态变更确认对话框 -->
      <el-dialog :title="confirmTitle" :visible.sync="showConfirm" width="30%" append-to-body>
        <div>
          <p style="text-align: center; margin: 20px 0;">确定要{{ confirmAction }}该客户吗？</p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showConfirm = false">取 消</el-button>
          <el-button type="primary" @click="confirmStatusChange">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>

import Pagination from "@/components/Pagination/index.vue"; // 分页组件，需确保项目中有
import RightToolbar from "@/components/RightToolbar/index.vue";
import { listCustomer, getCustomer, addCustomer, updateCustomer, checkCustomerRelation, enableCustomer, disableCustomer } from "@/api/erp/customer";



export default {
  name: "Customer",
  computed: {
    scope() {
      return scope
    }
  },
  components: { Pagination, RightToolbar },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看客户弹出层
      openView: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: undefined,
        customerName: undefined,
        status: undefined,
      },
      // 状态变更确认对话框
      showConfirm: false,
      confirmTitle: "",
      confirmAction: "",
      currentCustomer: null,
      // 列信息
      columns: {
        customerId: { label: "客户编号", visible: true },
        customerName: { label: "客户名称", visible: true },
        createTime: { label: "创建时间", visible: true },
        status: { label: "状态", visible: true },
      },
      // 表单校验
      rules: {
        customerId: [
          { required: true, message: "客户编号不能为空", trigger: "blur" },
          { min: 2, max: 30, message: "客户编号长度必须介于 2 和 30 之间", trigger: "blur" },
        ],
        customerName: [
          // 修改必填提示信息
          { required: true, message: "客户名称必填，请重新输入。", trigger: "blur" },
          // 修改格式和长度验证规则
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\W]{1,16}$/,
            message: "客户名称输入有误，请重新输入。",
            trigger: "blur"
          }
          ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listCustomer(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.customerList = response.rows;
        console.log(this.customerList)
        this.total = response.total;
        this.loading = false;

      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.customerId); // 假设客户主键为 customerId，需与后端一致
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: undefined,
        customerName: undefined,
        status: "启用",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
      this.form.status = "启用";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customerId = row.customerId || this.ids[0];
      getCustomer(customerId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const customerId = row.customerId || this.ids[0];
      getCustomer(customerId).then((response) => {
        this.form = response.data;
        this.openView = true;
        this.title = "查看客户";
      });
    },
    /** 关闭查看客户弹出层 */
    cancelView() {
      this.openView = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.customerId != undefined) {
            updateCustomer(this.form).then((response) => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then((response) => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 日期格式化（若项目中有 parseTime 工具函数，需确保引入）
    parseTime(time) {
      if (!time) return "";
      // 这里可根据项目中 parseTime 实际逻辑实现，示例：
      // return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
      return new Date(time).toLocaleString();
    },
    /** 处理启用操作 */
    handleEnable(row) {
      this.confirmTitle = "启用客户";
      this.confirmAction = "启用";
      this.currentCustomer = row;
      this.showConfirm = true;
    },

    /** 处理禁用操作 */
    handleDisable(row) {
      this.confirmTitle = "禁用客户";
      this.confirmAction = "禁用";
      this.currentCustomer = row;
      this.showConfirm = true;
    },

    /** 确认状态变更 */
    confirmStatusChange() {
      if (this.confirmAction === "启用") {
        this.doEnableCustomer();
      } else {
        this.doDisableCustomer();
      }
    },

    /** 执行启用客户 */
    doEnableCustomer() {
      enableCustomer(this.currentCustomer.customerId).then(response => {
        this.$message.success("客户启用成功");
        this.showConfirm = false;
        this.getList(); // 重新加载列表
      }).catch(error => {
        this.$message.error("操作失败：" + (error.msg || "系统错误"));
      });
    },


    /** 执行禁用客户 */
    doDisableCustomer() {
      // 先检查是否有流转中的关联单据
      checkCustomerRelation(this.currentCustomer.customerId)
        .then(hasRelation => {
          if (hasRelation) {
            this.$message.warning("客户关联单据流转中，无法禁用。");
            this.showConfirm = false;
          } else {
            // 没有关联单据，可以禁用
            disableCustomer(this.currentCustomer.customerId)
              .then(response => {
                this.$message.success("客户禁用成功");
                this.showConfirm = false;
                this.getList(); // 重新加载列表
              })
              .catch(error => {
                // 增强错误信息显示
                this.$message.error({
                  message: "禁用失败: " + (error.response?.data?.msg || error.message || "未知错误"),
                  duration: 5000
                });
                console.error("禁用客户错误详情:", error); // 打印详细错误到控制台
              });
          }
        })
        .catch(error => {
          // 增强错误信息显示
          this.$message.error({
            message: "检查关联失败: " + (error.response?.data?.msg || error.message || "未知错误"),
            duration: 5000
          });
          console.error("检查客户关联错误详情:", error); // 打印详细错误到控制台
        });
    },

  },
};
</script>

<style scoped lang="scss">

</style>
